package proprietary

import (
	"context"
	"github.com/pkg/errors"

	"github.com/brocaar/chirpstack-api/go/v3/gw"
	"github.com/brocaar/lorawan"
	"network/v3/internal/config"
)

const defaultCodeRate = "4/5"

type proprietaryContext struct {
	ctx context.Context

	MACPayload     []byte
	MIC            lorawan.MIC
	GatewayMACs    []lorawan.EUI64
	IPol           bool
	Frequency      int
	DR             int
	DownlinkFrames []gw.DownlinkFrame
}

var (
	downlinkTXPower    int
	ErrInvalidDataRate = errors.New("invalid data-rate")
)

// Setup configures the package.
func Setup(conf config.Config) error {
	downlinkTXPower = conf.NetworkServer.NetworkSettings.DownlinkTXPower

	return nil
}

// Handle handles a proprietary downlink.
func Handle(ctx context.Context, macPayload []byte, mic lorawan.MIC, gwMACs []lorawan.EUI64, iPol bool, frequency, dr int) error {
	pctx := proprietaryContext{
		ctx:         ctx,
		MACPayload:  macPayload,
		MIC:         mic,
		GatewayMACs: gwMACs,
		IPol:        iPol,
		Frequency:   frequency,
		DR:          dr,
	}

	return HandleRunTasks(&pctx)
}

func HandleRunTasks(pctx *proprietaryContext) error {
	for _, t := range tasks {
		if err := t(pctx); err != nil {
			return err
		}
	}

	return nil
}
